#include "Arduino.h"
#include "encoder.h"
#include "event.h"
#include "buzzer.h"
#include "power_management.h"
#include "screen.h"
#include "config.h"
#include <OneButton.h>  // 包含OneButton库头文件

/*
    新增用来检测编码器，单击，双击，旋转的函数实现
*/
// OneButton button2(ENCODER_KEY_PIN, true);
// ESP32Encoder encoder; // 只使用一个编码器
OneButton button2(ENCODER_KEY_PIN, true);
ESP32Encoder encoder;
int lastEncoderValue = 0;
unsigned long lastEncoderUpdateTime = 0;

void encoderClick() {
    ButtonEvent evt = {
        .type = EVENT_ENCODER_CLICK,
        .value = 0,
        .timestamp = millis()};
    xQueueSendFromISR(buttonEventQueue, &evt, NULL);
}

void encoderDoubleClick() {
    ButtonEvent evt = {
        .type = EVENT_ENCODER_DOUBLE_CLICK,
        .value = 0,
        .timestamp = millis()};
    xQueueSendFromISR(buttonEventQueue, &evt, NULL);
}

void init_encoder() {
    // 初始化编码器按钮,按键检测是按键这个对象的
    button2.attachClick(encoderClick);
    button2.attachDoubleClick(encoderDoubleClick);
    
    // 初始化编码器
    encoder.attachHalfQuad(ENCODER_B_PIN, ENCODER_A_PIN);
    encoder.setFilter(100); // 100us滤波消抖
    encoder.setCount(0);
}

void encoderTask(void *pvParameters) {
    while (true) {
        button2.tick(); // 处理编码器按钮
        
        int currentValue = encoder.getCount();
        unsigned long currentTime = millis();
        
        if (currentValue % 2 == 0 && (currentTime - lastEncoderUpdateTime >= 400)) {
            if (currentValue != lastEncoderValue) {
                // 更新状态
                encoderValue = currentValue;
                playBuzzer(beepLevel_g, 30, 0);
                lastEncoderValue = currentValue;
                lastEncoderUpdateTime = currentTime;
                update_encoder_activity();
                
                // 发送旋转事件
                ButtonEvent evt = {
                    .type = EVENT_ENCODER_ROTATE,
                    .value = currentValue,
                    .timestamp = currentTime};
                xQueueSend(buttonEventQueue, &evt, 0);
            }
        }
        vTaskDelay(50 / portTICK_PERIOD_MS);
    }
}